package com.zrc.japktool;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import javax.imageio.ImageIO;
import java.util.Locale;

public class MainApplication extends Application {

    private Stage primaryStage;
    private TrayIcon trayIcon;
    private SystemTray systemTray;
    private static final int SINGLE_INSTANCE_PORT = 49215; // 选择一个不常用的端口
    private static ServerSocket serverSocket;

    @Override
    public void start(Stage stage) throws IOException {
        // 检查是否已有实例运行
        if (!isFirstInstance()) {
            // 通知已运行的实例激活窗口，然后直接退出
            notifyExistingInstance();
            Platform.exit();
            return;
        }

        this.primaryStage = stage;

        FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("main-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 900, 600);

        // 设置应用程序图标
        try {
            InputStream iconStream = getClass().getResourceAsStream("/icons/logo.png");
            if (iconStream != null) {
                stage.getIcons().add(new Image(iconStream));
            }
        } catch (Exception e) {
            System.err.println("无法加载应用程序图标: " + e.getMessage());
        }

        stage.setTitle("JApkTool");
        stage.setScene(scene);
        stage.show();

        // 初始化系统托盘
        initSystemTray();

        // 启动激活监听器
        startActivationListener();

        // 设置关闭按钮的行为（隐藏到托盘）
        stage.setOnCloseRequest(event -> {
            event.consume(); // 阻止默认关闭行为
            hideToTray();
        });
    }

    /**
     * 检查是否为第一个实例
     * 使用端口锁定机制确保只有一个实例运行
     */
    private boolean isFirstInstance() {
        try {
            // 尝试绑定到指定端口
            serverSocket = new ServerSocket(SINGLE_INSTANCE_PORT, 10, InetAddress.getByAddress(new byte[]{127, 0, 0, 1}));

            // 添加关闭钩子，确保程序退出时释放端口
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                try {
                    if (serverSocket != null) {
                        serverSocket.close();
                    }
                } catch (IOException e) {
                    // 忽略关闭异常
                }
            }));

            return true;
        } catch (IOException e) {
            // 端口已被占用，说明已有实例运行
            return false;
        }
    }

    /**
     * 通知已运行的实例激活窗口
     */
    private void notifyExistingInstance() {
        try (Socket socket = new Socket("localhost", SINGLE_INSTANCE_PORT);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
            out.println("ACTIVATE");
        } catch (IOException e) {
            // 无法连接到已运行的实例，可能是实例刚刚退出
        }
    }

    /**
     * 启动激活监听器，用于接收来自其他实例的激活请求
     */
    private void startActivationListener() {
        Thread listenerThread = new Thread(() -> {
            while (!serverSocket.isClosed()) {
                try (Socket clientSocket = serverSocket.accept();
                     java.io.BufferedReader in = new java.io.BufferedReader(
                             new java.io.InputStreamReader(clientSocket.getInputStream()))) {

                    String message = in.readLine();
                    if ("ACTIVATE".equals(message)) {
                        Platform.runLater(() -> {
                            showFromTray();
                            primaryStage.toFront();
                        });
                    }
                } catch (IOException e) {
                    // Socket已关闭，正常退出
                    if (!serverSocket.isClosed()) {
                        System.err.println("激活监听器错误: " + e.getMessage());
                    }
                }
            }
        });

        listenerThread.setDaemon(true);
        listenerThread.start();
    }

    /**
     * 初始化系统托盘
     */
    private void initSystemTray() {
        // 检查系统是否支持托盘
        if (!SystemTray.isSupported()) {
            System.out.println("系统不支持托盘功能");
            return;
        }

        Platform.setImplicitExit(false); // 防止窗口关闭时程序退出
        systemTray = SystemTray.getSystemTray();

        // 使用更可靠的方式加载托盘图标
        java.awt.Image trayImage = null;
        try {
            // 方法1: 使用ImageIO读取图像（更可靠）
            URL imageUrl = getClass().getResource("/icons/logo.png");
            if (imageUrl != null) {
                trayImage = ImageIO.read(imageUrl);
            }

            // 方法2: 备用方法，如果ImageIO失败
            if (trayImage == null) {
                InputStream imageStream = getClass().getResourceAsStream("/icons/logo.png");
                if (imageStream != null) {
                    trayImage = ImageIO.read(imageStream);
                }
            }
        } catch (IOException e) {
            System.err.println("无法加载托盘图标: " + e.getMessage());
            // 创建默认的简单图标作为后备
            trayImage = createDefaultTrayImage();
        }

        // 如果图标加载失败，使用默认图标
        if (trayImage == null) {
            trayImage = createDefaultTrayImage();
        }

        trayIcon = new TrayIcon(trayImage, "JApkTool");

        // 设置托盘图标自动缩放
        trayIcon.setImageAutoSize(true);

        // 创建右键弹出菜单
        PopupMenu popup = new PopupMenu();

        // 直接使用中文字符串，不进行任何编码转换
        MenuItem exitItem = new MenuItem("退出");
        exitItem.addActionListener(e -> exitApplication());
        popup.add(exitItem);
        trayIcon.setPopupMenu(popup);

        // 添加鼠标监听器
        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                // 左键单击或双击显示窗口
                if (e.getButton() == MouseEvent.BUTTON1) {
                    Platform.runLater(() -> showFromTray());
                }
            }
        });

        try {
            systemTray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("无法添加托盘图标: " + e.getMessage());
        }
    }

    /**
     * 创建默认托盘图标（当资源图标无法加载时使用）
     */
    private java.awt.Image createDefaultTrayImage() {
        // 创建一个简单的默认图标
        int size = 16;
        java.awt.Image image = new java.awt.image.BufferedImage(size, size, java.awt.image.BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = (Graphics2D) image.getGraphics();

        // 绘制一个简单的蓝色方块
        g2d.setColor(Color.BLUE);
        g2d.fillRect(0, 0, size, size);
        g2d.setColor(Color.WHITE);
        g2d.drawString("J", size/2-3, size/2+4);
        g2d.dispose();

        return image;
    }

    /**
     * 隐藏窗口到系统托盘
     */
    private void hideToTray() {
        Platform.runLater(() -> {
            if (primaryStage != null) {
                primaryStage.hide();
            }
        });
    }

    /**
     * 从系统托盘显示窗口
     */
    private void showFromTray() {
        if (primaryStage != null) {
            primaryStage.show();
            primaryStage.toFront();
        }
    }

    /**
     * 退出应用程序
     */
    private void exitApplication() {
        // 移除托盘图标
        if (systemTray != null && trayIcon != null) {
            systemTray.remove(trayIcon);
        }

        // 关闭服务器Socket
        try {
            if (serverSocket != null) {
                serverSocket.close();
            }
        } catch (IOException e) {
            // 忽略关闭异常
        }

        // 退出应用程序
        Platform.exit();
        System.exit(0);
    }

    public static void main(String[] args) {
        System.setProperty("file.encoding", "UTF-8");// 设置系统属性以确保正确的字符编码
        Locale.setDefault(Locale.CHINA); // 设置默认区域设置
        System.setProperty("sun.awt.encoding", "UTF-8");// 强制设置AWT使用的编码
        launch(args);
    }
}